package jp.ne.motoki.android.ml14971;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;

public class ML14971Activity extends Activity {
    
    private Button button = null;
    
    private ExecutorService service;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        button = (Button) findViewById(R.id.button);
    }
    
    @Override
    public void onPause() {
        super.onPause();
        if (service != null) {
            stopTask();
        }
    }
    
    public void onClickButton(View view) {
        if (service == null) {
            startTask();
        } else {
            stopTask();
        }
    }
    
    private void startTask() {
        service = Executors.newSingleThreadExecutor();
        service.execute(new BackGroundTask(this, new Handler()));
        button.setText("Stop");
    }
    
    private void stopTask() {
        service.shutdownNow();  // shutDown()だと、インタラプトできないため。
        service = null;
        button.setText("Start");
    }
}